package hku.cs.lunuo.rank;

import hku.cs.lunuo.constant.DirAndFileConstant;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class BlkStatisticProvider extends StatisticProvider {

	@Override
	public Statistic readStatisticData(HashMap<String, Boolean> testResult) throws Exception {
		BlkStatistic data = new BlkStatistic();
		SAXBuilder sb = new SAXBuilder();
		for (String key : testResult.keySet()) {
			boolean tof = testResult.get(key);
			data.addTotaltf(tof);
			File tf = new File(dataDir, key);
			if (tf.exists() && tf.isDirectory()) {
				File f = new File(tf, DirAndFileConstant.BLOCK);
				if (f.exists() && f.isDirectory()) {
					String[] ffNames = f.list();

					for (int j = 0; j < ffNames.length; j++) {
						File ff = new File(f, ffNames[j]);
						if (ff.isFile() && ff.getName().indexOf("xml") >= 0) {
							Document xmlDoc = sb.build(ff);
							Element xmlRoot = (Element) xmlDoc.getRootElement();
							String className = xmlRoot
									.getAttributeValue("name");
							Iterator xmlMethodIt = xmlRoot
									.getChildren("method").iterator();
							while (xmlMethodIt.hasNext()) {
								Element xmlMethod = (Element) xmlMethodIt
										.next();
								String methodName = xmlMethod.getAttributeValue("name");
								
								Iterator xmlBlkIt = xmlMethod.getChildren(
										"block").iterator();
								

								while (xmlBlkIt.hasNext()) {
									Element xmlBlk = (Element) xmlBlkIt
											.next();
									int times = Integer.parseInt(xmlBlk
											.getAttributeValue("times"));
									int idx = Integer.parseInt(xmlBlk
											.getAttributeValue("index"));
									data.add(className, methodName, idx,
											times, tof);
								}
							}
						}

					}
				}
			}
		}
		return data;

	}

}
